<template>
  <div class="app-container">
    <search-form @formAction="handleSearch" v-show="state.showSearch">
      <template #default>
        <el-form label-position="top" :model="queryParams" ref="queryRef" :inline="true">
          <el-form-item label="父公司名称" prop="parentId">
            <ApiSelect
              v-model="queryParams.parentId"
              :options="parentOptions"
              valueField="companyId"
              labelField="name"
            />
          </el-form-item>
          <el-form-item label="公司名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="合作模式" prop="cooperationMode">
            <el-select v-model="queryParams.cooperationMode" placeholder="请选择" clearable>
              <el-option
                v-for="dict in sys_cooperation"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="公司地址" prop="address">
            <el-input v-model="queryParams.address" placeholder="请输入公司地址" />
          </el-form-item>
          <el-form-item label="状态" prop="enabled">
            <el-select v-model="queryParams.enabled" placeholder="请选择" clearable>
              <el-option
                v-for="dict in sys_common_staus"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="支付方式" prop="paymentCode">
            <el-select v-model="queryParams.paymentCode" placeholder="请选择" clearable>
              <el-option
                v-for="dict in sys_payment"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="营业执照有效期" prop="">
            <el-form-item prop="bizLicenceBeginTime" style="margin-right: 0">
              <el-date-picker
                v-model="queryParams.bizLicenceBeginTime"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="开始时间"
              />
            </el-form-item>
            ~&nbsp;
            <el-form-item prop="bizLicenceEndTime">
              <el-date-picker
                v-model="queryParams.bizLicenceEndTime"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="结束时间"
              />
            </el-form-item>
          </el-form-item>
          <el-form-item label="合同到期时间">
            <el-form-item prop="contractBeginDate" style="margin-right: 0">
              <el-date-picker
                v-model="queryParams.contractBeginDate"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="开始时间"
              />
            </el-form-item>
            ~&nbsp;
            <el-form-item prop="contractEndDate">
              <el-date-picker
                v-model="queryParams.contractEndDate"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="结束时间"
              />
            </el-form-item>
          </el-form-item>
        </el-form>
      </template>
    </search-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleAdd" v-hasPermi="['tissue:company:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="state.showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="state.loading" :data="tableList" :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="父公司账号" align="center" width="110">
        <template #default="{ row }">
          {{ row.parentCompanyAccount ?? '—' }}
        </template>
      </el-table-column>
      <el-table-column label="父公司名称" align="center" width="150">
        <template #default="{ row }">
          {{ row.parentName ?? '—' }}
        </template>
      </el-table-column>
      <el-table-column label="公司名称" align="center" prop="name" />
      <el-table-column label="公司账号" align="center" prop="companyAccount" width="120" />
      <el-table-column
        label="公司地址"
        align="center"
        prop="address"
        :show-overflow-tooltip="true"
        width="200"
      />
      <el-table-column label="营业执照有效期" align="center" prop="address" width="180">
        <template #default="{ row }">
          {{
            `${row?.bizLicenceBeginTime || ''}~${
              row?.longTerm == 1 ? '长期' : row?.bizLicenceEndTime || ''
            }`
          }}
        </template>
      </el-table-column>
      <el-table-column label="合作模式" align="center" width="90">
        <template #default="{ row }">
          <dict-tag :options="sys_cooperation" :value="row.cooperationMode" />
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" prop="paymentCode" width="90">
        <template #default="{ row }">
          <dict-tag :options="sys_payment" :value="row.paymentCode" />
        </template>
      </el-table-column>
      <el-table-column label="合同开始时间" width="110" align="center" prop="contractBeginDate" />
      <el-table-column label="合同到期时间" width="110" align="center" prop="contractEndDate" />
      <el-table-column label="状态" align="center" width="100">
        <template #default="{ row }">
          <dict-tag :options="sys_common_staus" :value="row.enabled" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="150">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleTableAction(row, 'detail')">查看</el-button>
          <el-button
            link
            type="primary"
            v-hasPermi="['tissue:company:edit']"
            @click="handleTableAction(row, 'edit')"
            >编辑</el-button
          >

          <ConfirmButton
            v-hasPermi="['tissue:company:dis']"
            :row="row"
            valueField="enabled"
            tipText="此公司"
            @confirm="handleTableAction"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--  -->
    <pagination
      v-show="state.total > 0"
      :total="state.total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="Company">
import { getListCompany, disableCompany } from '@/api/organization/company'
import { getParentCompanyById } from '@/api/organization/common'
import { onMountedOrActivated } from '@/hooks/common'
import useUserStore from '@/store/modules/user'
import { parseTime } from '@/utils/tools'

const useStore = useUserStore()
useStore.getAllCompany()
const router = useRouter()
const { proxy } = getCurrentInstance()
const { sys_payment, sys_cooperation, sys_common_staus } = proxy.useDict(
  'sys_payment',
  'sys_cooperation',
  'sys_common_staus'
)
const companyId = useStore.companyId
const queryRef = ref(null)
const tableList = ref([])
const parentOptions = ref([])
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})
const state = reactive({
  showSearch: true,
  total: 0,
  loading: false
})

// 获取父公司下拉框数据
onMounted(() => {
  getParentCompanyById(companyId).then((res) => {
    parentOptions.value = [{ companyId: '0', name: '无' }].concat(res?.data || [])
  })
})

// 搜索动作
function handleSearch(confirm) {
  if (!confirm) queryRef.value.resetFields()

  queryParams.value.pageNum = 1
  getList()
}

// table行样式处理
const tableRowClassName = ({ row }) => (row.warning ? 'warning-row' : '')
// 数据拉取
async function getList() {
  state.loading = true
  // 下个月日期，合同到期提醒
  const nextMonthDate = parseTime(
    new Date(new Date().setMonth(new Date().getMonth() + 1)),
    '{y}-{m}-{d}'
  )

  try {
    const r = await getListCompany(queryParams.value)
    const data = r?.rows || []
    tableList.value = data?.map((item) => {
      const endTime = item.contractEndDate

      if (endTime && endTime <= nextMonthDate) item.warning = true
      return item
    })
    state.total = r?.total
  } finally {
    state.loading = false
  }
}

/**table Action */
function handleAdd() {
  router.push({ path: '/organization/addCompany' })
}
function handleTableAction(obj, operType) {
  if (operType == 'auth') {
    disableCompany({ id: obj.companyId, enabled: obj.enabled }).then(() => {
      proxy.$modal.msgSuccess('操作成功')
      getList()
    })
  } else {
    const path = operType == 'edit' ? '/organization/editCompany' : '/organization/companyDetail'
    router.push({ path, query: { id: obj.companyId } })
  }
}

/**init +  onActivated*/
onMountedOrActivated(getList)
</script>

<style lang="scss" scoped>
:deep(.warning-row) {
  background-color: var(--el-color-error-light-5);
}
</style>
